﻿/*************************************
 * Creator:SW-PeiYang
 * DateTime:2023/11/21 14:19:11
 * Description:<Description>
 * CopyRight:中广核研究院有限公司
 * ***********************************/

using System;
using System.Net;

namespace Cpjit.SunnyPaine.Toolkit.Net.Sockets.Util
{
    /// <summary>
    /// IP地址工具。
    /// </summary>
    public static class IPAddressUtil
    {
        /// <summary>
        /// 将IP端口转换为终结点。
        /// </summary>
        /// <param name="ipAddress">符合127.0.0.1:8000规范的IP地址。</param>
        /// <returns></returns>
        public static EndPoint ToEndPoint(this string ipAddress)
        {
            string[] strs = ipAddress.Split(':');
            return new IPEndPoint(IPAddress.Parse(strs[0]), int.Parse(strs[1]));
        }

        /// <summary>
        /// 将终结点转换为IP端口。
        /// </summary>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public static string ToIPAddress(this EndPoint endPoint)
        {
            return endPoint.ToString();
        }

        /// <summary>
        /// 获取IP。
        /// </summary>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public static string GetIP(this EndPoint endPoint)
        {
            string ipAddress = endPoint.ToString();
            string[] strs = ipAddress.Split(':');
            return strs[0];
        }

        /// <summary>
        /// 获取端口。
        /// </summary>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public static int GetPort(this EndPoint endPoint)
        {
            string ipAddress = endPoint.ToString();
            string[] strs = ipAddress.Split(':');
            return int.Parse(strs[1]);
        }

        /// <summary>
        /// 获取IP端口。
        /// </summary>
        /// <param name="endPoint"></param>
        /// <returns>返回包含IP和端口的元组。Item1：IP，Item2：端口。</returns>
        public static Tuple<string, int> GetIpPort(this EndPoint endPoint)
        {
            string ipAddress = endPoint.ToString();
            string[] strs = ipAddress.Split(':');
            return new Tuple<string, int>(strs[0], int.Parse(strs[1]));
        }

        /// <summary>
        /// 创建EndPoint的一个深拷贝副本。
        /// </summary>
        /// <param name="endPoint"></param>
        /// <returns></returns>
        public static EndPoint Copy(this EndPoint endPoint)
        {
            Tuple<string, int> tuple = endPoint.GetIpPort();
            return new IPEndPoint(IPAddress.Parse(tuple.Item1), tuple.Item2);
        }
    }
}
